/**
 * Created by lijtg on 2015/10/21.
 */
$(document).ready(function () {
    var main = {
        config: {
        },
        cache: {
            timer: null,
            radios: $("input[name='radio-legal-agent']:checked"),
            legalBox: $('#legal-box'),
            agentBox: $('#agent-box'),
            in1Box: $('#3in1-box'),
            notIn1Box: $('#not-3in1-box'),
            legalOrAgent: '01',
            in1: true,
            imgBase64: {
                legal_p: '',
                legal_r: '',
                agent_p: '',
                agent_r: '',
                in1: '',
                business: '',
                tax: '',
                org: ''
            }
        },
        startTimer: function () {
            var btn = $('#pr-btn-msgCode');
            var time = 60;
            btn.attr('disabled', 'disabled');
            btn.html('重新发送(' + time + 'S)');
            main.cache.timer = setInterval(function () {
                if(time < 0){
                    btn.attr('disabled', false);
                    btn.html('重新发送');
                    clearInterval(main.cache.timer);
                    return;
                }
                btn.html('重新发送(' + time-- + 'S)');
            }, 1000);
        },
        sendMsgCode: function (){
            var btn = $('#pr-btn-msgCode');
            if(btn.attr('disabled') == 'disabled') return;
            var phone = $('#pr-phone').val();
            if(!common.isMobile(phone)) {
                common.alertLayer({
                    errMsg: '联系人手机号有误'
                });
                return;
            }
            $.ajax({
                type: "POST",
                url: common.hostPath + "/api/sendMsgCode",
                data: {
                    phone: phone
                },
                dataType : 'json',
                success: function (data) {
                    if (data.errCode == "000000") {
                        main.startTimer();
                    }
                    else {
                        common.responseFail(data)
                    }
                },
                complete: function(){
                    //main.startTimer();
                },
                error: common.responseError
            });
        },
        submit: function (){
            var btn = $('#pr-btn-submit');
            if(btn.attr('disabled') == 'disabled') return;
            if(!main.formCheck(3)) return;

            var name = $.trim($('#en-name').val());
            var email = $.trim($('#en-email').val());
            var addr = $.trim($('#en-addr').val());
            var agentName = $.trim($('#pr-agentName').val());
            var agentDocId = $.trim($('#pr-agentDocId').val());
            var legalName = $.trim($('#pr-legalName').val());
            var legalDocId = $.trim($('#pr-legalDocId').val());
            var unifyCode = $.trim($('#en-unifyCode').val());
            var businessCode = $.trim($('#en-businessCode').val());
            var cardId = $.trim($('#pr-cardId').val());
            var cardName = $.trim($('#pr-cardName').val());
            var cardBank = $.trim($('#pr-cardBank').val());
            var transPwd = $.trim($('#pr-transPwd').val());
            var legalDocType = $('#pr-legalDocType').val();
            var agentDocType = $('#pr-agentDocType').val();

            if(main.cache.legalOrAgent == '01'){
                agentName = '';
                agentDocId = '';
                main.cache.imgBase64.agent_p = '';
                main.cache.imgBase64.agent_r = '';
            }
            if(main.cache.in1){
                businessCode = '';
                main.cache.imgBase64.business = '';
                main.cache.imgBase64.tax = '';
                main.cache.imgBase64.org = '';
            }
            else{
                unifyCode = '';
                main.cache.imgBase64.in1 = '';
            }

            $.ajax({
                type: "POST",
                url: common.hostPath + "/api/eOpenAcct",
                data: {
                    OPTION: '01',
                    PRODUCT_TYPE: '',
                    PWD_TYPE: 'WD',
                    PASSWORD: depositEncrypt.encryptByDES(transPwd),
                    CHECK_NAME_FLAG: '01',
                    LINKED_AGGR_TYPE: '01',
                    LINKED_BASE_ACCT_NO: cardId,
                    LINKED_ACCT_NAME: cardName,
                    LINKED_BANK_CODE: '',
                    LINKED_BANK_NAME: cardBank,
                    LINKED_ACCT_CD_TYPE: '06',
                    REG_ID: email,
                    CATEGORY_TYPE: '',
                    CUSTOMER_SHORT: '',
                    CUSTOMER_NAME: name,
                    ADDRESS: addr,
                    COUNTRY_RISK: '',
                    STATE: '',
                    CLIENT_CITY: '',
                    COUNTRY_CITIZEN: '',
                    COUNTRY_REGION_CODE: '',
                    INLAND_OFFSHORE: '',
                    INDUSTRY: '',
                    INTERNAL_IND: '',
                    CLIENT_INDICATOR: '',
                    CUSTOMER_MANAGER_ID: '',
                    ORGAN_CODE: '',
                    ORIGIN_COUNTRY: '',
                    CAPITAL_CCY: '',
                    SCALE: '',
                    BASIC_ACCT_NO: '',
                    AUTH_CAPITAL: '',
                    REGISTER_NO_TYPE: '',
                    REGISTER_NO: businessCode,
                    TAX_FILE_NO: '',
                    ORGAN: '',
                    UNIFIED_SOCIAL_CREDIT_CODE: unifyCode,
                    BUS_LICENCE_PHOTO: main.cache.imgBase64.business,
                    TAX_REGIS_PHOTO: main.cache.imgBase64.tax,
                    ORG_CODE_PHOTO: main.cache.imgBase64.org,
                    ALL_LICENCE_PHOTO: main.cache.imgBase64.in1,
                    IS_LEGAL_OR_PRINCIPAL: main.cache.legalOrAgent == '01' ? '0' : '1',
                    LEGAL_REP: legalName,
                    REP_IDENTIFICATION_TYPE: legalDocType,
                    REP_IDENTIFICATION_NUMBER: legalDocId,
                    REP_ISS_DATE: '',
                    REP_EXPIRY_DATE: '',
                    LEGAL_ID_PHOTO1: main.cache.imgBase64.legal_p,
                    LEGAL_ID_PHOTO2: main.cache.imgBase64.legal_r,
                    AGENT: agentName,
                    AGENT_DOC_TYPE: agentDocType,
                    AGENT_DOC_ID: agentDocId,
                    AGENT_ID_PHOTO1: main.cache.imgBase64.agent_p,
                    AGENT_ID_PHOTO2: main.cache.imgBase64.agent_r,
                    LOAN_CARD_ID: '',
                    CONTACT_METHOD_TYPE: '',
                    CONTACT_NUMBER: '',
                    EMAIL: email,
                    NOTIFY_METHOD: ''
                },
                dataType : 'json',
                success: function (data) {
                    if (data.errCode == "000000") {
                        layer.open({
                            content: '注册成功',
                            btn: '确定'
                        });
                    }
                    else {
                        common.responseFail(data)
                    }
                },
                complete: function(){
                    btn.attr('disabled', false);
                },
                error: common.responseError
            });
        },
        stepForward: function (step) {
            var line0 = $('.pr-step-container .pr-step-line-0');
            var line1 = $('.pr-step-container .pr-step-line-1');
            var width = line0.css('width');
            var number = $('.pr-step-container .pr-step-item-number');
            var text = $('.pr-step-container .pr-step-text');
            var index = step - 1;
            var percent = (parseInt(width) / 2 * index) / parseInt($('.pr-step-container').css('width')) * 100;

            line1.css('width', percent + '%');
            $(number[index]).addClass('pr-step-item-number-active');
            $(text[index]).addClass('pr-step-text-active');
        },
        stepBackWard: function (step) {
            var line0 = $('.pr-step-container .pr-step-line-0');
            var line1 = $('.pr-step-container .pr-step-line-1');
            var width = line0.css('width');
            var number = $('.pr-step-container .pr-step-item-number');
            var text = $('.pr-step-container .pr-step-text');
            var index = step - 1;
            var percent = (parseInt(width) / 2 * index) / parseInt($('.pr-step-container').css('width')) * 100;

            line1.css('width', percent + '%');
            $(number[index + 1]).removeClass('pr-step-item-number-active');
            $(text[index + 1]).removeClass('pr-step-text-active');
        },
        formCheck: function (currentStep) {
            if(currentStep == 1){
                var name = $.trim($('#en-name').val());
                if(name == '') {
                    common.alertLayer({
                        errMsg: '企业名称有误'
                    });
                    return false;
                }

                var email = $.trim($('#en-email').val());
                if(!common.isEmail(email)) {
                    common.alertLayer({
                        errMsg: '企业邮箱有误'
                    });
                    return false;
                }

                var addr = $.trim($('#en-addr').val());
                if(addr == '') {
                    common.alertLayer({
                        errMsg: '企业地址有误'
                    });
                    return false;
                }

                //经办人
                if(main.cache.legalOrAgent == '02'){
                    var agentName = $.trim($('#pr-agentName').val());
                    if(agentName == '') {
                        common.alertLayer({
                            errMsg: '经办人姓名有误'
                        });
                        return false;
                    }
                    var agentDocId = $.trim($('#pr-agentDocId').val());
                    if(agentDocId == '') {
                        common.alertLayer({
                            errMsg: '经办人证件号码有误'
                        });
                        return false;
                    }
                    if(main.cache.imgBase64.agent_p == '') {
                        common.alertLayer({
                            errMsg: '请上传经办人身份证正面照'
                        });
                        return false;
                    }
                    if(main.cache.imgBase64.agent_r == '') {
                        common.alertLayer({
                            errMsg: '请上传经办人身份证反面照'
                        });
                        return false;
                    }
                }

                //法人或经办人，都需校验法人信息
                if(main.cache.legalOrAgent == '01' || main.cache.legalOrAgent == '02'){
                    var legalName = $.trim($('#pr-legalName').val());
                    if(legalName == '') {
                        common.alertLayer({
                            errMsg: '法人姓名有误'
                        });
                        return false;
                    }
                    var legalDocId = $.trim($('#pr-legalDocId').val());
                    if(legalDocId == '') {
                        common.alertLayer({
                            errMsg: '法人证件号码有误'
                        });
                        return false;
                    }
                    if(main.cache.imgBase64.legal_p == '') {
                        common.alertLayer({
                            errMsg: '请上传法人身份证正面照'
                        });
                        return false;
                    }
                    if(main.cache.imgBase64.legal_r == '') {
                        common.alertLayer({
                            errMsg: '请上传法人身份证反面照'
                        });
                        return false;
                    }
                }
            }

            if(currentStep == 2){
                if(main.cache.in1){
                    var unifyCode = $.trim($('#en-unifyCode').val());
                    if(unifyCode == '') {
                        common.alertLayer({
                            errMsg: '统一社会信用代码有误'
                        });
                        return false;
                    }
                    if(main.cache.imgBase64.in1 == '') {
                        common.alertLayer({
                            errMsg: '请上传三证合一照片'
                        });
                        return false;
                    }
                }
                else{
                    var businessCode = $.trim($('#en-businessCode').val());
                    if(businessCode == '') {
                        common.alertLayer({
                            errMsg: '营业执照号有误'
                        });
                        return false;
                    }
                    if(main.cache.imgBase64.business == '') {
                        common.alertLayer({
                            errMsg: '请上传营业执照照片'
                        });
                        return false;
                    }
                    if(main.cache.imgBase64.tax == '') {
                        common.alertLayer({
                            errMsg: '请上传税务登记证照片'
                        });
                        return false;
                    }
                    if(main.cache.imgBase64.org == '') {
                        common.alertLayer({
                            errMsg: '请上传组织机构代码证照片'
                        });
                        return false;
                    }
                }

                var cardId = $.trim($('#pr-cardId').val());
                if(cardId == '' ||
                    cardId.length < 16 ||
                    cardId.length > 19) {
                    common.alertLayer({
                        errMsg: ' 企业账户卡号有误'
                    });
                    return false;
                }
                var cardName = $.trim($('#pr-cardName').val());
                if(cardName == '') {
                    common.alertLayer({
                        errMsg: '企业账户名称有误'
                    });
                    return false;
                }
                var cardBank = $.trim($('#pr-cardBank').val());
                if(cardBank == '') {
                    common.alertLayer({
                        errMsg: '开户行名称有误'
                    });
                    return false;
                }
            }

            if(currentStep == 3) {
                var transPwd = $.trim($('#pr-transPwd').val());
                if (isNaN(transPwd) || transPwd.length != 6) {
                    common.alertLayer({
                        errMsg: ' 交易密码有误'
                    });
                    return false;
                }

                var transPwdConfirm = $.trim($('#pr-transPwdConfirm').val());
                if (transPwdConfirm != transPwd) {
                    common.alertLayer({
                        errMsg: ' 两次输入不一致'
                    });
                    return false;
                }
            }

            return true;
        },
        goNext: function (step) {
            //校验
            if(!main.formCheck(step - 1)) return;

            main.stepForward(step);
            $('#container-' + (step - 1)).hide(1);
            $('#container-' + step).show(1);
        },
        goPre: function (step) {
            //校验
            //if(!main.formCheck()) return;

            main.stepBackWard(step);
            $('#container-' + (step + 1)).hide(1);
            $('#container-' + step).show(1);
        },
        chooseImg: function (cfg) {
            $('#' + cfg.btn).on('click', function (ev) {
                $('#' + cfg.id).click();
            });
            $('#' + cfg.id).on('change', function () {
                lrz(this.files[0])
                    .then(function (rst) {
                        // 处理成功会执行
                        var img = new Image();
                        main.cache.imgBase64[cfg.cache] = img.src = rst.base64;
                        $('#' + cfg.view).html('').append(img)
                            .find('img').css('width', '100%').css('height', '100%');
                    }).catch(function (err) {
                        // 处理失败会执行
                    }).always(function () {
                        // 不管是成功失败，都会执行
                    });
            });
        },
        regHammer: function () {
            $('.radio-inline').each(function (index, item) {
                //var hammer = new Hammer(item);
                //hammer.on('tap', function (ev) {
                $(item).on('click', function () {
                    main.cache.legalOrAgent = $("input[name='radio-legal-agent']:checked").val();
                    if(main.cache.legalOrAgent == '01'){
                        main.cache.legalBox.show();
                        main.cache.agentBox.hide();
                    }
                    else{
                        main.cache.legalBox.show();
                        main.cache.agentBox.show();
                    }
                });
            });
            var hammer1 = new Hammer($('#pr-btn-next')[0]);
            hammer1.on('tap', function (ev) {
                main.goNext(2);
            });
            var hammer2 = new Hammer($('#pr-btn-next2')[0]);
            hammer2.on('tap', function (ev) {
                main.goNext(3);
            });
            var hammer3 = new Hammer($('#pr-btn-pre2')[0]);
            hammer3.on('tap', function (ev) {
                main.goPre(1);
            });
            var hammer4 = new Hammer($('#pr-btn-submit')[0]);
            hammer4.on('tap', function (ev) {
                main.submit();
            });
            var hammer5 = new Hammer($('#pr-btn-pre3')[0]);
            hammer5.on('tap', function (ev) {
                main.goPre(2);
            });
        },
        init: function () {
            main.regHammer();
            $('#en-3in1').on('change', function () {
                if($(this)[0].checked){
                    main.cache.in1 = true;
                    main.cache.in1Box.show();
                    main.cache.notIn1Box.hide();
                }
                else{
                    main.cache.in1 = false;
                    main.cache.in1Box.hide();
                    main.cache.notIn1Box.show();
                }
            });
            $('#pr-agree').on('change', function () {
                if($(this)[0].checked){
                    $('#pr-btn-submit').attr('disabled', false);
                }
                else{
                    $('#pr-btn-submit').attr('disabled', 'disabled');
                }
            });
            $('#pr-legalDocType').select2();
            $('#pr-agentDocType').select2();

            main.chooseImg({id: 'legal-docImage-input-p', btn: 'legal-btn-docImage-p', view: 'legal-docImage-p-view', cache: 'legal_p'});
            main.chooseImg({id: 'legal-docImage-input-r', btn: 'legal-btn-docImage-r', view: 'legal-docImage-r-view', cache: 'legal_r'});
            main.chooseImg({id: 'agent-docImage-input-p', btn: 'agent-btn-docImage-p', view: 'agent-docImage-p-view', cache: 'agent_p'});
            main.chooseImg({id: 'agent-docImage-input-r', btn: 'agent-btn-docImage-r', view: 'agent-docImage-r-view', cache: 'agent_r'});
            main.chooseImg({id: 'en-3in1-img', btn: 'en-btn-3in1-img', view: 'en-3in1-img-view', cache: 'in1'});
            main.chooseImg({id: 'en-business-img', btn: 'en-btn-business-img', view: 'en-business-img-view', cache: 'business'});
            main.chooseImg({id: 'en-tax-img', btn: 'en-btn-tax-img', view: 'en-tax-img-view', cache: 'tax'});
            main.chooseImg({id: 'en-org-img', btn: 'en-btn-org-img', view: 'en-org-img-view', cache: 'org'});
        }
    };

    main.init();
});